import React, { useState, useEffect } from 'react'
import { Plus, Search, Edit, Trash2, Filter } from 'lucide-react'

function UserManagement() {
  const [users, setUsers] = useState([])
  const [searchTerm, setSearchTerm] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [editingUser, setEditingUser] = useState(null)
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    role: 'user',
    status: 'active'
  })

  useEffect(() => {
    loadUsers()
  }, [])

  const loadUsers = async () => {
    setIsLoading(true)
    try {
      // 这里应该调用后端API获取用户列表
      // const response = await fetch('/api/users')
      // const data = await response.json()
      // setUsers(data)
      
      // 模拟数据
      setTimeout(() => {
        setUsers([
          { id: 1, username: 'admin', email: 'admin@example.com', role: '管理员', status: 'active', createdAt: '2024-01-15' },
          { id: 2, username: 'user1', email: 'user1@example.com', role: '用户', status: 'active', createdAt: '2024-01-20' },
          { id: 3, username: 'user2', email: 'user2@example.com', role: '用户', status: 'inactive', createdAt: '2024-01-25' },
          { id: 4, username: 'operator', email: 'operator@example.com', role: '操作员', status: 'active', createdAt: '2024-02-01' }
        ])
        setIsLoading(false)
      }, 1000)
    } catch (error) {
      console.error('加载用户列表失败:', error)
      setIsLoading(false)
    }
  }

  const handleEdit = (user) => {
    setEditingUser(user)
    setFormData({
      username: user.username,
      email: user.email,
      role: user.role,
      status: user.status
    })
    setShowCreateModal(true)
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    try {
      if (editingUser) {
        // 更新用户逻辑
        console.log('更新用户:', editingUser.id, formData)
        // 这里应该调用后端API更新用户
      } else {
        // 创建用户逻辑
        console.log('创建用户:', formData)
        // 这里应该调用后端API创建用户
      }
      
      setShowCreateModal(false)
      setEditingUser(null)
      setFormData({
        username: '',
        email: '',
        role: 'user',
        status: 'active'
      })
      await loadUsers()
    } catch (error) {
      console.error('保存用户失败:', error)
      alert('保存用户失败')
    }
  }

  const handleDelete = async (id) => {
    if (confirm('确定要删除这个用户吗？')) {
      try {
        // 这里应该调用后端API删除用户
        console.log('删除用户:', id)
        await loadUsers()
      } catch (error) {
        console.error('删除用户失败:', error)
        alert('删除用户失败')
      }
    }
  }

  const resetForm = () => {
    setEditingUser(null)
    setFormData({
      username: '',
      email: '',
      role: 'user',
      status: 'active'
    })
    setShowCreateModal(false)
  }

  const filteredUsers = users.filter(user =>
    user.username.toLowerCase().includes(searchTerm.toLowerCase()) ||
    user.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
    user.role.toLowerCase().includes(searchTerm.toLowerCase())
  )

  const getStatusColor = (status) => {
    return status === 'active' ? 'bg-green-500' : 'bg-red-500'
  }

  const getRoleColor = (role) => {
    const colors = {
      '管理员': 'bg-purple-500',
      '操作员': 'bg-blue-500',
      '用户': 'bg-gray-500'
    }
    return colors[role] || 'bg-gray-500'
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="bg-white/10 backdrop-blur-lg rounded-2xl p-6 border border-white/20">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-white mb-2">用户管理</h1>
            <p className="text-blue-200">管理系统用户账户和权限设置</p>
          </div>
          <button
            onClick={() => setShowCreateModal(true)}
            className="flex items-center px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg font-medium transition-colors duration-200"
          >
            <Plus className="h-4 w-4 mr-2" />
            创建用户
          </button>
        </div>
      </div>

      {/* Search and Filter */}
      <div className="bg-white/10 backdrop-blur-lg rounded-2xl p-6 border border-white/20">
        <div className="flex items-center space-x-4">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-blue-300 h-4 w-4" />
            <input
              type="text"
              placeholder="搜索用户名、邮箱或角色..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2 bg-gray-800 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-blue-500"
            />
          </div>
          <button className="flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium transition-colors duration-200">
            <Filter className="h-4 w-4 mr-2" />
            筛选
          </button>
        </div>
      </div>

      {/* Users Table */}
      <div className="bg-white/10 backdrop-blur-lg rounded-2xl border border-white/20 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-white/10">
                <th className="px-6 py-3 text-left text-xs font-medium text-blue-200 uppercase tracking-wider">用户信息</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-blue-200 uppercase tracking-wider">角色</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-blue-200 uppercase tracking-wider">状态</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-blue-200 uppercase tracking-wider">创建时间</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-blue-200 uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-white/5">
              {filteredUsers.map((user) => (
                <tr key={user.id} className="hover:bg-white/5 transition-colors duration-200">
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div>
                      <div className="text-sm font-medium text-white">{user.username}</div>
                      <div className="text-sm text-blue-300">{user.email}</div>
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium text-white ${getRoleColor(user.role)}`}>
                      {user.role}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium text-white ${getStatusColor(user.status)}`}>
                      {user.status === 'active' ? '活跃' : '禁用'}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-blue-300">{user.createdAt}</td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div className="flex items-center space-x-2">
                      <button 
                        onClick={() => handleEdit(user)}
                        className="text-blue-400 hover:text-blue-300 transition-colors duration-200"
                      >
                        <Edit className="h-4 w-4" />
                      </button>
                      <button 
                        onClick={() => handleDelete(user.id)}
                        className="text-red-400 hover:text-red-300 transition-colors duration-200"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        
        {isLoading && (
          <div className="p-8 text-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mx-auto"></div>
            <p className="text-blue-300 mt-2">加载中...</p>
          </div>
        )}
        
        {!isLoading && filteredUsers.length === 0 && (
          <div className="p-8 text-center">
            <p className="text-blue-300">未找到匹配的用户</p>
          </div>
        )}
      </div>

      {/* Create/Edit User Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="bg-gray-900 rounded-2xl p-6 w-full max-w-md border border-white/20">
            <h3 className="text-xl font-bold text-white mb-4">
              {editingUser ? '编辑用户' : '创建新用户'}
            </h3>
            
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="block text-blue-200 text-sm font-medium mb-2">用户名</label>
                <input
                  type="text"
                  value={formData.username}
                  onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                  className="w-full px-3 py-2 bg-gray-800 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-blue-500"
                  placeholder="请输入用户名"
                  required
                />
              </div>
              
              <div>
                <label className="block text-blue-200 text-sm font-medium mb-2">邮箱</label>
                <input
                  type="email"
                  value={formData.email}
                  onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                  className="w-full px-3 py-2 bg-gray-800 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-blue-500"
                  placeholder="请输入邮箱地址"
                  required
                />
              </div>
              
              <div>
                <label className="block text-blue-200 text-sm font-medium mb-2">角色</label>
                <select 
                  value={formData.role}
                  onChange={(e) => setFormData({ ...formData, role: e.target.value })}
                  className="w-full px-3 py-2 bg-gray-800 border border-gray-600 rounded-lg text-white focus:outline-none focus:border-blue-500"
                >
                  <option value="用户">用户</option>
                  <option value="操作员">操作员</option>
                  <option value="管理员">管理员</option>
                </select>
              </div>

              <div>
                <label className="block text-blue-200 text-sm font-medium mb-2">状态</label>
                <select 
                  value={formData.status}
                  onChange={(e) => setFormData({ ...formData, status: e.target.value })}
                  className="w-full px-3 py-2 bg-gray-800 border border-gray-600 rounded-lg text-white focus:outline-none focus:border-blue-500"
                >
                  <option value="active">活跃</option>
                  <option value="inactive">禁用</option>
                </select>
              </div>
            </form>
            
            <div className="flex items-center justify-end space-x-3 mt-6">
              <button
                onClick={resetForm}
                className="px-4 py-2 text-blue-300 hover:text-white transition-colors duration-200"
              >
                取消
              </button>
              <button 
                onClick={handleSubmit}
                className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg font-medium transition-colors duration-200"
              >
                {editingUser ? '更新' : '创建'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default UserManagement